package com.jhy.suixianglu.daima20230113;

/**
 * 请实现一个函数，把字符串 s 中的每个空格替换成"%20"。
 * 输入：s = "We are happy."
 * 输出："We%20are%20happy."
 */
public class ReplaceSpace {
    public String replaceSpace(String s) {

        if(s == null || s.length() == 0){
            return s;
        }
        // 首先算出来空格的数目是多少
        StringBuilder str = new StringBuilder();
        for (int i = 0; i < s.length(); i++) {
            if (s.charAt(i) == ' ') {
                str.append("  ");
            }
        }
        if (str.length() == 0) {
            return s;
        }
        // 前一个指针
        int left = s.length() - 1;
        s += str.toString();
        // 后一个指针
        int right = s.length() - 1;
        char[] chars = s.toCharArray();
        while (left<right) {
            if (chars[left] == ' ') {
                chars[right] = '0';
                chars[right-1] = '2';
                chars[right-1] = '%';
                right-=2;
            } else {
                chars[right] = chars[left];
            }
            left--;
            right--;

        }
        return new String(chars);
    }

}
